//
//  RegisterViewController.m
//  OCPB
//
//  Created by Siroj Chongkolwanont on 6/27/56 BE.
//  Copyright (c) 2556 Siroj Chongkolwanont. All rights reserved.
//

#import "RegisterViewController.h"
#import "Province.h"
#import "Aumphur.h"
#import "Tumbon.h"
#import "UserInfo.h"

@interface RegisterViewController ()

@end

@implementation RegisterViewController

@synthesize pickerView1;
@synthesize pickerView2;
@synthesize pickerView3;
@synthesize IdText;
@synthesize passText;
@synthesize firstText;
@synthesize lastText;
@synthesize telText;
@synthesize emailText;
@synthesize postText;
@synthesize userInfo;
@synthesize mode;
@synthesize registerBtn;
@synthesize addrText;
@synthesize authorizationData;

@synthesize userInfo_nameText;
@synthesize userInfo_telText;
@synthesize userInfo_emailText;
@synthesize userInfo_address;
@synthesize provinceTextbox;
@synthesize aumphurText;
@synthesize tumbolText;
@synthesize scrollView;
@synthesize confirmPasswordText;

@synthesize provinceButton;
@synthesize aumphurButton;
@synthesize tumbolButton;

NSMutableArray *provinceArray;
NSMutableArray *aumphurArray;
NSMutableArray *tumbonArray;
NSMutableData* responseData;

Province* currentProvince;
Aumphur* currentAumphur;
Tumbon*  currentTumbon;
UserInfo* userInfo;

UITextField* currentTextView;
UIActionSheet* aProvinceSheet;
UIActionSheet* aAumphurSheet;
UIActionSheet* aTumbonSheet;









-(BOOL)textFieldShouldReturn:(UITextField*)textField;
{
    
    if(textField == IdText)
    {
        [passText becomeFirstResponder];
    }
    
    if(textField == passText)
    {
        [confirmPasswordText becomeFirstResponder];
    }
    
    if(textField == confirmPasswordText)
    {
        [firstText becomeFirstResponder];
    }
    
    if(textField == firstText)
    {
        [lastText becomeFirstResponder];
    }
    
    if(textField == lastText)
    {
        [addrText becomeFirstResponder];
    }
    
    if(textField == addrText)
    {
        //[provinceTextbox becomeFirstResponder];
        [provinceButton sendActionsForControlEvents: UIControlEventTouchUpInside];

    }
    
    if(textField == postText)
    {
        [telText becomeFirstResponder];
    
    }
    
    if(textField == telText)
    {
        [emailText becomeFirstResponder];
    }
    
    if(textField == emailText)
    {
        [textField resignFirstResponder];
    }
    
    return NO; // We do not want UITextField to insert line-breaks.
}


id jsonObjectFromUrlString(NSString *urlString)
{
    NSURL *url = [NSURL URLWithString:urlString];
    NSError *error = nil;
    id jsonObject = nil;
    NSData *data = [NSData dataWithContentsOfURL:url options:NSDataReadingUncached error:&error];
    if(error)
        NSLog(@"%@", error);
    else
        jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
    if(error)
        NSLog(@"%@", error);
    return jsonObject;
}



- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView;
{
    // The number of sections in the UIPickerView
    
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component;
{
    // The number of rows in the UIPickerView
    //return [pickerData count];
    
    if(pickerView == pickerView1)
        
     return [provinceArray count];
    
    else if (pickerView == pickerView2)
        return [aumphurArray count];
    
    else if (pickerView == pickerView3)
        return [tumbonArray count];
    
    return  0;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component;
{
    // The data for each row in the UIPickerView
    //return [pickerData objectAtIndex:row];
    
    if(pickerView == pickerView1)
    {
        return  ((Province*)provinceArray[row]).prov_thai;
        
    }
    
    else if(pickerView == pickerView2)
    {
        return ((Aumphur*)aumphurArray[row]).aump_name;
        
    }
    else if(pickerView == pickerView3)
    {
        
        return ((Tumbon*)tumbonArray[row]).tum_name;
    }
    
    return @"";
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    // whatever you want to happen when a row is selected.
    
    // here I am assuming you want to remove from the picker and add to the table on selection
    
    if(pickerView == pickerView1)
    {
        [self load_aumphur:provinceArray[row]];
        [self load_tumbon:aumphurArray[0]];
        
        [pickerView2 reloadAllComponents];
        [pickerView3 reloadAllComponents];
        
        currentProvince = provinceArray[row];
        
    }
    else if(pickerView == pickerView2)
    {
        [self load_tumbon:aumphurArray[row]];
        [pickerView3 reloadAllComponents];
        
        currentAumphur = aumphurArray[row];
        
    }
    else if (pickerView == pickerView3)
    {
        currentTumbon = tumbonArray[row];
    }

}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void) showAction:(id)sender
{
    UIActionSheet *asheet = nil;
    
    if(sender == provinceButton)
    {
        asheet = aProvinceSheet;
    }
    else if (sender == aumphurButton)
    {
        asheet = aAumphurSheet;
    }
    else if (sender == tumbolButton)
    {
        asheet = aTumbonSheet;
    }
    
    [asheet setFrame:CGRectMake(0, 117, 320, 383)];
    
    [asheet showInView:[self.view superview]];
    
    
    UIScrollView* v = (UIScrollView*) scrollView ;
    CGRect rc = [sender bounds];
    rc = [sender convertRect:rc toView:v];
    
    rc.origin.x = 0 ;
    rc.origin.y -= 60 ;
    
    rc.size.height = 400;
    [scrollView setContentOffset:CGPointMake(rc.origin.x, rc.origin.y)
                        animated:YES];
}


- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //Get the name of the current pressed button
    
    if(actionSheet == aProvinceSheet)
    {
        currentProvince = provinceArray[buttonIndex];
        [provinceButton setTitle:currentProvince.prov_thai forState:UIControlStateNormal];
        [self load_aumphur:currentProvince];
        
        [aumphurButton sendActionsForControlEvents: UIControlEventTouchUpInside];
        
    }
    else if (actionSheet == aAumphurSheet)
    {
        currentAumphur = aumphurArray[buttonIndex];
        [aumphurButton setTitle:currentAumphur.aump_name forState:UIControlStateNormal];
        [self load_tumbon:currentAumphur];
        [tumbolButton sendActionsForControlEvents: UIControlEventTouchUpInside];
                
    }
    else if(actionSheet == aTumbonSheet)
    {
        currentTumbon = tumbonArray[buttonIndex];
        [tumbolButton setTitle:currentTumbon.tum_name forState:UIControlStateNormal];
        
        [postText becomeFirstResponder];
        
    }
    
    
}


-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    if(textField.tag == 1 )
        pickerView1.hidden = NO;
    else if (textField.tag ==2 )
        pickerView2.hidden = NO;
    else if (textField.tag ==3 )
        pickerView3.hidden = NO;
    
    currentTextView = textField;
    
    textField.inputView = nil;
    
    
    //if(textField.tag == 6 || textField.tag == 9)
    {
    
        UIScrollView* v = (UIScrollView*) scrollView ;
        CGRect rc = [currentTextView bounds];
        rc = [currentTextView convertRect:rc toView:v];
        
        rc.origin.x = 0 ;
        rc.origin.y -= 60 ;
        
        rc.size.height = 400;
        [scrollView setContentOffset:CGPointMake(rc.origin.x, rc.origin.y)
                            animated:YES];
    }
    
}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    if(textField == emailText )
    {
        [self checkEmailAndDisplayAlert];
    }
}

- (BOOL)validateEmail:(NSString *)emailStr {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,10}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:emailStr];
}

- (void)checkEmailAndDisplayAlert {
    if(![self validateEmail:[emailText text]]) {
        // user entered invalid email address
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Enter a valid email address."
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
        emailText.text = @"";
    } else {
        // user entered valid email address
    }
}

- (BOOL)textView:(UITextView *)textView
shouldChangeTextInRange:(NSRange)range
 replacementText:(NSString *)text
{
    

    
    if ([text isEqualToString:@"\n"])
    {
        [textView resignFirstResponder];
    }
    return YES;
}

- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

{
    if ([string length] == 0 && range.length > 0)
    {
        return YES;
    }
    
    
    if (textField== postText &&  [textField.text length] == 5)
    {
        [textField resignFirstResponder];
        
        if(textField == postText)
        {
            [telText becomeFirstResponder];
        }
    }
    
    if (textField== telText &&  [textField.text length] == 10)
    {
        [textField resignFirstResponder];
        
        [emailText becomeFirstResponder];
    }
    
    if (textField== IdText &&  [textField.text length] == 13)
    {
        [textField resignFirstResponder];
        
        if ([mode isEqualToString:@"edit"])
        {
            [firstText becomeFirstResponder];
        }
        else
        {
            [passText becomeFirstResponder];
        }
    }
    
    
    
    if ([string isEqualToString:@"\n"])
    {
        [textField resignFirstResponder];
    }
    
    
    

    if ([string length] == 0 && range.length > 0)
    {
       return YES;
    }
    
    
    NSCharacterSet* notDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
    if ([string rangeOfCharacterFromSet:notDigits].location != NSNotFound && (textField== postText|| textField == telText|| textField== IdText) )
    {
        return NO;
    }
    

    return YES;
    
}


- (void)load_province
{
    provinceArray = [[NSMutableArray alloc] init];
    
    NSDictionary *publicTimeline =  jsonObjectFromUrlString(@"http://www.aitproject.com/demo/webservice/public/service/province");
    
    aProvinceSheet = [[UIActionSheet alloc] initWithTitle:@"เลือกจังหวัด" delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil, nil];

    
    for(NSString *item in [publicTimeline allKeys]) {
        
        if([item isEqual: @"data"] )
        {
            NSArray *allDara = [publicTimeline valueForKey:item];
            
            for(NSDictionary *dara in allDara )
            {
                Province* province = [[Province alloc] init];
                province.prov_code = [dara valueForKey:@"Prov_code"];
                province.prov_thai = [dara valueForKey:@"Prov_nameT"];
                province.prov_eng = [dara valueForKey:@"prov_nameE"];
                
                [aProvinceSheet addButtonWithTitle:province.prov_thai];

                
                [provinceArray addObject:province];
            }
            
        }
    }
    
    if(provinceArray.count  > 0)
    currentProvince = provinceArray[0];
}

- (void)load_aumphur:(Province*)province
{
    aumphurArray = [[NSMutableArray alloc] init];
   
    NSString *aumphur_str = [NSString stringWithFormat:@"http://www.aitproject.com/demo/webservice/public/service/aumphur?id=%@", province.prov_code];
    
    
    NSDictionary *publicTimeline =  jsonObjectFromUrlString(aumphur_str);
    
    aAumphurSheet = [[UIActionSheet alloc] initWithTitle:@"เลือกอำเภอ" delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil, nil];
    
    
    for(NSString *item in [publicTimeline allKeys]) {
        
        if([item isEqual: @"data"] )
        {
            NSArray *allData = [publicTimeline valueForKey:item];
            
            for(NSDictionary *data in allData )
            {
                Aumphur* aumphur = [[Aumphur alloc] init];
                aumphur.prov_code = [data valueForKey:@"prov_code"];
                aumphur.aump_code = [data valueForKey:@"aump_code"];
                aumphur.aump_name = [data valueForKey:@"aump_name"];
                
                [aAumphurSheet addButtonWithTitle:aumphur.aump_name];
                
                [aumphurArray addObject:aumphur];
            }
            
        }
    }
    
    if(aumphurArray.count  > 0)
    currentAumphur = aumphurArray[0];

}



- (void)load_tumbon:(Aumphur*)aumphur
{
    tumbonArray = [[NSMutableArray alloc] init];
    
    NSString *tumbon_str = [NSString stringWithFormat:@"http://www.aitproject.com/demo/webservice/public/service/tumbon?id=%@&prov_code=%@", aumphur.aump_code,aumphur.prov_code];
    
    
    NSDictionary *publicTimeline =  jsonObjectFromUrlString(tumbon_str);
    
    
    aTumbonSheet = [[UIActionSheet alloc] initWithTitle:@"เลือกตำบล" delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil, nil];
    
    
    for(NSString *item in [publicTimeline allKeys]) {
        
        if([item isEqual: @"data"] )
        {
            NSArray *allData = [publicTimeline valueForKey:item];
            
            for(NSDictionary *data in allData )
            {
                Tumbon* tumbon = [[Tumbon alloc] init];
                tumbon.prov_code = [data valueForKey:@"PROV_CODE"];
                tumbon.tum_code = [data valueForKey:@"TUMB_CODE"];
                tumbon.aump_code = [data valueForKey:@"AUMP_CODE"];
                tumbon.tum_name = [data valueForKey:@"TUMB_NAME"];
                tumbon.zip_code = [data valueForKey:@"TUMB_ZIPCODE"];
                
                [tumbonArray addObject:tumbon];
                
                [aTumbonSheet addButtonWithTitle:tumbon.tum_name];
            }
            
        }
    }
    
    if(tumbonArray.count  > 0)
    currentTumbon = tumbonArray[0];
}


- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [responseData setLength:0];
}


-(void)userInfo_reloadData
{
    userInfo_nameText.text = [NSString stringWithFormat: @"%@ %@", userInfo.fName, userInfo.lName];
    userInfo_telText.text = userInfo.mobile;
    userInfo_emailText.text = userInfo.email;
    userInfo_address.text = userInfo.address;
}
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if ([mode isEqualToString:@"edit"])
    {
        [self userInfo_reloadData];
        [self.navigationController popViewControllerAnimated:YES];
    }
    else
    {
        //[self performSegueWithIdentifier:@"toLogin" sender:self];
        [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed: @"New_Navigation_background_320x46.png"]
                                                      forBarMetrics:UIBarMetricsDefault];
       [self.navigationController popViewControllerAnimated:NO];


    }
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    NSError *error = nil;
    //NSString *jsonResponse =  [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSDictionary* jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
    
   NSString* error_code = [jsonObject valueForKey:@"error_code"];
    
    
    NSString *jsonRequest =  [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    NSLog(@"jsonResponse is %@", jsonRequest);
    
   if(error_code.intValue > 0)
   {
       UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"ระบบร้องทุกข์!"
                                                         message:[jsonObject valueForKey:@"message"]
                                                        delegate:nil
                                               cancelButtonTitle:@"ตกลง"
                                               otherButtonTitles:nil];
       [message show];
       
   }
   else
   {
       if ([mode isEqualToString:@"edit"])
       {
           UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"ระบบร้องทุกข์!"
                                                             message:[jsonObject valueForKey:@"message"]
                                                            delegate:self
                                                   cancelButtonTitle:@"ตกลง"
                                                   otherButtonTitles:nil];
           [message show];
           
           //self.userInfo = [[UserInfo alloc] init];
           
           //userInfo.mobile = userInfo_telText.text;
           //userInfo_emailText.text = userInfo.email;
           //userInfo_address.text = userInfo.address;
           
           for(NSString *item in [jsonObject allKeys]) {
               
               if([item isEqual: @"data"] )
               {
                   NSDictionary *userInfoJSON = [jsonObject valueForKey:item];
                   
                   if (![[userInfoJSON valueForKey:@"Petitioner_password"] isKindOfClass:[NSNull class]])
                   {
                       userInfo.password = (NSString *)[userInfoJSON valueForKey:@"Petitioner_password"];
                   }
                   if (![[userInfoJSON valueForKey:@"Petitioner_FName"] isKindOfClass:[NSNull class]])
                   {
                       userInfo.fName = (NSString *)[userInfoJSON valueForKey:@"Petitioner_FName"];
                   }
                   if (![[userInfoJSON valueForKey:@"Petitioner_LName"] isKindOfClass:[NSNull class]])
                   {
                       userInfo.lName = (NSString *)[userInfoJSON valueForKey:@"Petitioner_LName"];
                       //nameText.text = [NSString stringWithFormat: @"%@ %@", userInfo.fName, userInfo.lName];
                   }
                   if (![[userInfoJSON valueForKey:@"Petitioner_IDCard"] isKindOfClass:[NSNull class]])
                   {
                       userInfo.idNumber = (NSString *)[userInfoJSON valueForKey:@"Petitioner_IDCard"];
                       //idNumberText.text = [userInfoJSON valueForKey:@"Petitioner_IDCard"];
                   }
                   if (![[userInfoJSON valueForKey:@"Petitioner_Username"] isKindOfClass:[NSNull class]])
                   {
                       userInfo.username = (NSString *)[userInfoJSON valueForKey:@"Petitioner_Username"];
                   }
                   if (![[userInfoJSON valueForKey:@"Tumbol_id"] isKindOfClass:[NSNull class]])
                   {
                       userInfo.tumbol_id = (NSString *)[userInfoJSON valueForKey:@"Tumbol_id"];
                   }
                   if (![[userInfoJSON valueForKey:@"Amphur_id"] isKindOfClass:[NSNull class]])
                   {
                       userInfo.amphur_id = (NSString *)[userInfoJSON valueForKey:@"Amphur_id"];
                   }
                   if (![[userInfoJSON valueForKey:@"Province_id"] isKindOfClass:[NSNull class]])
                   {
                       userInfo.province_id = (NSString *)[userInfoJSON valueForKey:@"Province_id"];
                   }
                   if (![[userInfoJSON valueForKey:@"PostCode"] isKindOfClass:[NSNull class]])
                   {
                       userInfo.postCode = (NSString *)[userInfoJSON valueForKey:@"PostCode"];
                   }
                   if (![[userInfoJSON valueForKey:@"Petitioner_mobile"] isKindOfClass:[NSNull class]])
                   {
                       NSString *mobile = [userInfoJSON valueForKey:@"Petitioner_mobile"];
                       userInfo.mobile = mobile;                     
                   }
                   if (![[userInfoJSON valueForKey:@"Petitioner_mail"] isKindOfClass:[NSNull class]])
                   {
                       userInfo.email = (NSString *)[userInfoJSON valueForKey:@"Petitioner_mail"];
                       //emailText.text = [userInfoJSON valueForKey:@"Petitioner_mail"];
                   }
                   if (![[userInfoJSON valueForKey:@"Address"] isKindOfClass:[NSNull class]])
                   {
                       userInfo.address = (NSString *)[userInfoJSON valueForKey:@"Address"];
                       //address.text = (NSString *)[userInfoJSON valueForKey:@"Address"];
                   }
               }
           }
       }
       else
       {
           UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"OCPB!"
                                                             message:@"สมัครสมาชิกเรียบร้อย"
                                                            delegate:self
                                                   cancelButtonTitle:@"OK"
                                                   otherButtonTitles:nil];
           [message show];
       }
       //[self.navigationController popViewControllerAnimated:YES];
   }
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"ลงชื่อเข้าใช้"
                                                      message:@"ไม่สามารถเชื่อมต่ออินเตอร์เน็ทได้ กรุณาตรวจสอบการตั้งค่าที่โทรศัพท์"
                                                     delegate:nil
                                            cancelButtonTitle:@"OK"
                                            otherButtonTitles:nil];
    [message show];

}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
}

- (void)doneTapped
{
    [currentTextView resignFirstResponder];
    
   
    
    if(currentTextView.tag == 1)
    {
        
        
        currentTextView.text = currentProvince.prov_thai;
        [aumphurText becomeFirstResponder];
        
        UIScrollView* v = (UIScrollView*) scrollView ;
        CGRect rc = [aumphurText bounds];
        rc = [aumphurText convertRect:rc toView:v];
        
        rc.origin.x = 0 ;
        rc.origin.y -= 60 ;
        
        rc.size.height = 400;
        [scrollView setContentOffset:CGPointMake(rc.origin.x, rc.origin.y)
                            animated:YES];
    }
    else if (currentTextView.tag ==2)
    {
        currentTextView.text = currentAumphur.aump_name;
        [tumbolText becomeFirstResponder];
        
        UIScrollView* v = (UIScrollView*) scrollView;
        CGRect rc = [tumbolText bounds];
        rc = [tumbolText convertRect:rc toView:v];
        
        rc.origin.x = 0 ;
        rc.origin.y -= 60 ;

        
        rc.size.height = 400;
        
        [scrollView setContentOffset:CGPointMake(rc.origin.x, rc.origin.y )
                            animated:YES];
        
    }
    else if (currentTextView.tag == 3)
    {
        currentTextView.text = currentTumbon.tum_name;
        
        [postText becomeFirstResponder];
    }
    
}

-(Province*) findProvince:(int) provinceId
{
    Province* province = NULL;
    
    for(int i=0; i < [provinceArray count]; ++i)
    {
        if(((Province*)provinceArray[i]).prov_code.intValue == provinceId )
        {
            province = provinceArray[i];
            break;
        }
    }
    
    return province;
}

-(int) findRowProvince:(int) provinceId
{
    int row = 0;
    
    for(int i=0; i < [provinceArray count]; ++i)
    {
        if(((Province*)provinceArray[i]).prov_code.intValue == provinceId )
        {
            row = i;
            break;
        }
    }
    
    return row;
}


-(Aumphur*) findAumphur:(int) aumphurId
{
    Aumphur* aumphur = NULL;
    
    for(int i=0; i < [aumphurArray count]; ++i)
    {
        if(((Aumphur*)aumphurArray[i]).aump_code.intValue == aumphurId )
        {
            aumphur = aumphurArray[i];
            break;
        }
    }
    
    return aumphur;
}

-(int) findRowAumphur:(int) aumphurId
{
    int row = 0;
    
    for(int i=0; i < [aumphurArray count]; ++i)
    {
        if(((Aumphur*)aumphurArray[i]).aump_code.intValue == aumphurId )
        {
            row = i;
            break;
        }
    }
    
    return row;
}


-(Tumbon*) findTumbol:(int) TumbolId
{
    Tumbon* tumbol = NULL;
    
    for(int i=0; i < [tumbonArray count]; ++i)
    {
        if(((Tumbon*)tumbonArray[i]).tum_code.intValue == TumbolId )
        {
            tumbol = tumbonArray[i];
            break;
        }
    }
    
    return tumbol;
}

-(int) findRowTumbol:(int) TumbolId
{
    int row = 0;
    
    for(int i=0; i < [tumbonArray count]; ++i)
    {
        if(((Tumbon*)tumbonArray[i]).tum_code.intValue == TumbolId )
        {
            row = i;
            break;
        }
    }
    
    return row;
}

- (IBAction)backAction:(id)sender {
    
    
    if(![mode isEqualToString:@"edit"])
    {
        [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed: @"New_Navigation_background_320x46.png"]
                                                      forBarMetrics:UIBarMetricsDefault];
    }
    
    [self.navigationController popViewControllerAnimated:NO];
}

-(void)dismissKeyboard {
    if(currentTextView != Nil)
        [currentTextView resignFirstResponder];
}


- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    BOOL editable;
    if (textField == provinceTextbox) {
        editable = NO;
    }  else {
        editable = YES;
    }
    return editable;
}




- (void)viewDidLoad
{
    UIToolbar* accessoryView = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
    accessoryView.barStyle = UIBarStyleBlackTranslucent;
    
    UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    
    UIBarButtonItem *done = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneTapped)];
    
    accessoryView.items = [NSArray arrayWithObjects:space,done, nil];
    
    
   //[[self navigationController] setNavigationBarHidden:NO animated:NO];
    
   // provinceTextbox.inputAccessoryView = accessoryView;
    aumphurText.inputAccessoryView = accessoryView;
    tumbolText.inputAccessoryView = accessoryView;
    
    //provinceTextbox.;
    
    provinceTextbox.inputView = nil;
    aumphurText.inputView = pickerView2;
    tumbolText.inputView = pickerView3;
    
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
                                   initWithTarget:self
                                   action:@selector(dismissKeyboard)];
    
    [self.view addGestureRecognizer:tap];
    
    
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed: @"22Navigation_background_320x46.png"]
                                                  forBarMetrics:UIBarMetricsDefault];
    
    
    UIButton *button1 = [[UIButton alloc] init];
    button1.frame= CGRectMake(0,0,43,32);
    [button1 setBackgroundImage:[UIImage imageNamed: @"bottom_home.png"] forState:UIControlStateNormal];
    
    [button1 addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:button1];
    
    
    if ([mode isEqualToString:@"edit"])
    {
        NSLog(@"edit user data");
        self.navigationItem.title = @"เเก้ไขข้อมูลส่วนตัว";
        [registerBtn setImage:[UIImage imageNamed:@"n_icon3.png"] forState:UIControlStateNormal];
        [self load_province];
        
        [IdText setEnabled:NO];

        IdText.text = userInfo.idNumber;
        firstText.text = userInfo.fName;
        lastText.text = userInfo.lName;
        telText.text = userInfo.mobile;
        emailText.text = userInfo.email;
        postText.text = userInfo.postCode;
        addrText.text = userInfo.address;
        
        [pickerView1 selectRow:[self findRowProvince:userInfo.province_id.intValue] inComponent:0 animated:false];
        currentProvince = [self findProvince:userInfo.province_id.intValue];
        
        [self load_aumphur:currentProvince];
        [pickerView2 selectRow:[self findRowAumphur:userInfo.amphur_id.intValue] inComponent:0 animated:false];
        
        
        
        currentAumphur = [self findAumphur:userInfo.amphur_id.intValue];
        
        [self load_tumbon:currentAumphur];
        [pickerView3 selectRow:[self findRowTumbol:userInfo.tumbol_id.intValue]  inComponent:0 animated:false];
        
        currentTumbon = [self findTumbol:userInfo.tumbol_id.intValue];
        
        //provinceTextbox.text = currentProvince.prov_thai;
        //aumphurText.text = currentAumphur.aump_name;
        //tumbolText.text = currentTumbon.tum_name;
        
        [provinceButton setTitle:currentProvince.prov_thai forState:UIControlStateNormal];
        [aumphurButton setTitle:currentAumphur.aump_name forState:UIControlStateNormal];
        [tumbolButton setTitle:currentTumbon.tum_name forState:UIControlStateNormal];
        
        [super viewDidLoad];
    }
    else
    {
        self.navigationItem.title = @"สมัครสมาชิก";
        //[registerBtn setTitle:@"สมัครสมาชิก" forState:UIControlStateNormal];
        [registerBtn setImage:[UIImage imageNamed:@"bottom.png"] forState:UIControlStateNormal];
        [IdText setEnabled:YES];
        [self load_province];
        if(provinceArray.count > 0 )
        {
           [self load_aumphur:provinceArray[0]];
           [self load_tumbon:aumphurArray[0]];
        }
        [super viewDidLoad];
    }
	// Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



- (IBAction)RegisterClick:(id)sender {
 
    
    NSArray *objects;
    NSArray *keys;

    if ([mode isEqualToString:@"edit"])
    {
        objects = [NSArray arrayWithObjects:addrText.text
                   ,currentAumphur.aump_code
                   ,firstText.text
                   ,IdText.text
                   ,IdText.text
                   ,lastText.text
                   ,emailText.text
                   ,telText.text
                   ,postText.text
                   ,currentProvince.prov_code
                   ,currentTumbon.tum_code
                   ,nil];
        
        keys = [NSArray arrayWithObjects:@"Address"
                ,@"Amphur_id"
                ,@"Petitioner_FName"
                ,@"Petitioner_IDCard"
                ,@"Petitioner_Username"
                ,@"Petitioner_LName"
                ,@"Petitioner_mail"
                ,@"Petitioner_mobile"
                ,@"PostCode"
                ,@"Province_id"
                ,@"Tumbol_id"
                ,nil];
    }
    else
    {
        

        
        
        if([IdText text].length  < 13)
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"สมัครสมาชิกไม่ได้" message:@"รหัสบัตรประจำตัวประชาชนไม่ครบ 13 หลัก"
                                                           delegate:nil
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil];
            [alert show];
            
            return;
        }
        
        if([confirmPasswordText.text isEqual:passText.text] == false)
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"สมัครสมาชิกไม่ได้" message:@"รหัสผ่านเเละยืนยันรหัสผ่านไม่ตรงกัน"
                                                           delegate:nil
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil];
            [alert show];
            
            return;
            
        }
        
        NSCharacterSet* Digits = [NSCharacterSet decimalDigitCharacterSet];
        
        NSCharacterSet* notDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
        
        NSString* passStr = [passText text];
        
        
        if (passStr.length  < 8)
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"สมัครสมาชิกไม่ได้" message:@"รหัสผ่านต้องมีความยาวอย่างน้อย 8 หลัก"
                                                           delegate:nil
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil];
            [alert show];
            
            return;
        }
        
        
        if ( [passStr rangeOfCharacterFromSet:notDigits].location == NSNotFound   || [passStr rangeOfCharacterFromSet:Digits].location == NSNotFound )
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"สมัครสมาชิกไม่ได้" message:@"รหัสผ่านต้องประกอบด้วยตัวอักษรหรือตัวเลขอย่างน้อย 1 ตัว"
                                                           delegate:nil
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil];
            [alert show];
            
            return;
        }
        
        
        if([passText.text isEqual: @""]
           || [firstText.text isEqual: @""]
           || [lastText.text isEqual: @""]
           || [IdText.text isEqual: @""]
           || [tumbolButton.titleLabel.text isEqual: @""]
           || [aumphurButton.titleLabel.text isEqual: @""]
           || [provinceButton.titleLabel.text isEqual: @""]
           || [telText.text isEqual: @""]
           || [emailText.text isEqual: @""]
           
           )
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"สมัครสมาชิกไม่ได้" message:@"คุณกรอกข้อมูลไม่ครบถ้วน"
                                                           delegate:nil
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil];
            [alert show];
            
            return;
            
        }
        
        objects = [NSArray arrayWithObjects:passText.text
                            , addrText.text
                            , firstText.text
                            , lastText.text
                            , IdText.text
                            , IdText.text
                            , currentTumbon.tum_code
                            ,currentAumphur.aump_code
                            ,currentProvince.prov_code
                            ,postText.text
                            ,telText.text
                            ,emailText.text
                            ,nil];
        keys = [NSArray arrayWithObjects:@"Petitioner_password"
                         ,@"Address"
                         ,@"Petitioner_FName"
                         ,@"Petitioner_LName"
                         ,@"Petitioner_IDCard"
                         ,@"Petitioner_Username"
                         ,@"Tumbol_id"
                         ,@"Amphur_id"
                         ,@"Province_id"
                         ,@"PostCode"
                         ,@"Petitioner_mobile"
                         ,@"Petitioner_mail"
                         ,nil];

    }
    
    NSDictionary *jsonDict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
    
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict
                                                       options:NSJSONWritingPrettyPrinted
                                                         error:&error];
    
    
    NSString *jsonRequest = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    NSLog(@"jsonRequest is %@", jsonRequest);
    
    NSURL *url;
    if ([mode isEqualToString:@"edit"])
    {
        url = [NSURL URLWithString:@"http://www.aitproject.com/demo/webservice/public/service/petitioner?method=PUT"];
    }
    else
    {
        url = [NSURL URLWithString:@"http://www.aitproject.com/demo/webservice/public/service/petitioner"];
    }
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    
     NSData *requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding]; //[NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
    
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
    
    if ([mode isEqualToString:@"edit"])
    {
        [request setValue:authorizationData  forHTTPHeaderField:@"Authorization"];
    }

    
    [request setHTTPBody: requestData];
    
    NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
    
    
    
    if (connection) {
        responseData = [[NSMutableData alloc] init];
    }
    
    
    
}

-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if([segue.identifier isEqualToString:@"userToRegister"])
    {
        NSLog(@"test");
    }
}

- (IBAction)selectList:(id)sender {
    
        [self showAction:sender];
    
}
@end
